{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "import pickle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['train_texts', 'test_texts', 'train_clss', 'test_clss', 'train_labels', 'test_labels'])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "with open('dataset.pkl', 'rb') as fopen:\n",
    "    dataset = pickle.load(fopen)\n",
    "dataset.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "73967"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(dataset['train_texts'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dictionary.pkl', 'rb') as fopen:\n",
    "    dictionary = pickle.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "rev_dictionary = dictionary['rev_dictionary']\n",
    "dictionary = dictionary['dictionary']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def position_encoding(inputs):\n",
    "    T = tf.shape(inputs)[1]\n",
    "    repr_dim = inputs.get_shape()[-1].value\n",
    "    pos = tf.reshape(tf.range(0.0, tf.to_float(T), dtype=tf.float32), [-1, 1])\n",
    "    i = np.arange(0, repr_dim, 2, np.float32)\n",
    "    denom = np.reshape(np.power(10000.0, i / repr_dim), [1, -1])\n",
    "    enc = tf.expand_dims(tf.concat([tf.sin(pos / denom), tf.cos(pos / denom)], 1), 0)\n",
    "    return tf.tile(enc, [tf.shape(inputs)[0], 1, 1])\n",
    "\n",
    "def layer_norm(inputs, epsilon=1e-8):\n",
    "    mean, variance = tf.nn.moments(inputs, [-1], keep_dims=True)\n",
    "    normalized = (inputs - mean) / (tf.sqrt(variance + epsilon))\n",
    "    params_shape = inputs.get_shape()[-1:]\n",
    "    gamma = tf.get_variable('gamma', params_shape, tf.float32, tf.ones_initializer())\n",
    "    beta = tf.get_variable('beta', params_shape, tf.float32, tf.zeros_initializer())\n",
    "    return gamma * normalized + beta\n",
    "\n",
    "\n",
    "def cnn_block(x, dilation_rate, pad_sz, hidden_dim, kernel_size):\n",
    "    x = layer_norm(x)\n",
    "    pad = tf.zeros([tf.shape(x)[0], pad_sz, hidden_dim])\n",
    "    x =  tf.layers.conv1d(inputs = tf.concat([pad, x, pad], 1),\n",
    "                          filters = hidden_dim,\n",
    "                          kernel_size = kernel_size,\n",
    "                          dilation_rate = dilation_rate)\n",
    "    x = x[:, :-pad_sz, :]\n",
    "    x = tf.nn.relu(x)\n",
    "    return x\n",
    "\n",
    "class Model:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size,\n",
    "                 dict_size, learning_rate, kernel_size = 3):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.float32, [None, None])\n",
    "        self.mask = tf.placeholder(tf.int32, [None, None])\n",
    "        self.clss = tf.placeholder(tf.int32, [None, None])\n",
    "        mask = tf.cast(self.mask, tf.float32)\n",
    "        encoder_embeddings = tf.Variable(tf.random_uniform([dict_size, embedded_size], -1, 1))\n",
    "        encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n",
    "        encoder_embedded += position_encoding(encoder_embedded)\n",
    "        \n",
    "        for i in range(num_layers): \n",
    "            dilation_rate = 2 ** i\n",
    "            pad_sz = (kernel_size - 1) * dilation_rate \n",
    "            with tf.variable_scope('block_%d'%i,reuse=False):\n",
    "                encoder_embedded += cnn_block(encoder_embedded, dilation_rate, \n",
    "                                              pad_sz, size_layer, kernel_size)\n",
    "                        \n",
    "        outputs = tf.gather(encoder_embedded, self.clss, axis = 1, batch_dims = 1)\n",
    "        self.logits = tf.layers.dense(outputs, 1)\n",
    "        self.logits = tf.squeeze(self.logits, axis=-1)\n",
    "        self.logits = self.logits * mask\n",
    "        crossent = tf.nn.sigmoid_cross_entropy_with_logits(logits=self.logits, labels=self.Y)\n",
    "        crossent = crossent * mask\n",
    "        crossent = tf.reduce_sum(crossent)\n",
    "        total_size = tf.reduce_sum(mask)\n",
    "        self.cost = tf.div_no_nan(crossent, total_size)\n",
    "        \n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        \n",
    "        l = tf.round(tf.sigmoid(self.logits))\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(tf.boolean_mask(l, tf.equal(self.Y, 1)), tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 256\n",
    "num_layers = 4\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-6-2231f555135a>:4: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n",
      "WARNING:tensorflow:From <ipython-input-6-2231f555135a>:25: conv1d (from tensorflow.python.layers.convolutional) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.keras.layers.Conv1D` instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From <ipython-input-6-2231f555135a>:54: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/nn_impl.py:180: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Model(size_layer,num_layers,embedded_size,len(dictionary),learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "UNK = 3\n",
    "\n",
    "def str_idx(corpus, dic):\n",
    "    X = []\n",
    "    for i in corpus:\n",
    "        ints = []\n",
    "        for k in i.split():\n",
    "            ints.append(dic.get(k,UNK))\n",
    "        X.append(ints)\n",
    "    return X\n",
    "\n",
    "def pad_sentence_batch(sentence_batch, pad_int):\n",
    "    padded_seqs = []\n",
    "    seq_lens = []\n",
    "    max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n",
    "    for sentence in sentence_batch:\n",
    "        padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n",
    "        seq_lens.append(len(sentence))\n",
    "    return padded_seqs, seq_lens"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = str_idx(dataset['train_texts'], dictionary)\n",
    "test_X = str_idx(dataset['test_texts'], dictionary)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_clss = dataset['train_clss']\n",
    "test_clss = dataset['test_clss']\n",
    "train_Y = dataset['train_labels']\n",
    "test_Y = dataset['test_labels']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0.36363637, 0.80718136)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x, _ = pad_sentence_batch(train_X[:5], 0)\n",
    "batch_y, _ = pad_sentence_batch(train_Y[:5], 0)\n",
    "batch_clss, _ = pad_sentence_batch(train_clss[:5], -1)\n",
    "batch_clss = np.array(batch_clss)\n",
    "batch_mask = 1 - (batch_clss == -1)\n",
    "batch_clss[batch_clss == -1] = 0\n",
    "\n",
    "feed = {model.X: batch_x,\n",
    "        model.Y: batch_y,\n",
    "        model.mask: batch_mask,\n",
    "        model.clss: batch_clss}\n",
    "acc, loss, _ = sess.run([model.accuracy, model.cost,model.optimizer], feed_dict = feed)\n",
    "acc, loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [05:11<00:00,  1.86it/s, accuracy=0, cost=0.268]      \n",
      "minibatch loop: 100%|██████████| 145/145 [00:21<00:00,  6.74it/s, accuracy=0, cost=0.221]     \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 0.267856, training avg acc 0.003014\n",
      "epoch 1, testing avg loss 0.253723, testing avg acc 0.000193\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.42it/s, accuracy=0.0106, cost=0.265] \n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.66it/s, accuracy=0, cost=0.222]      \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 0.252464, training avg acc 0.001037\n",
      "epoch 2, testing avg loss 0.253672, testing avg acc 0.001260\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.43it/s, accuracy=0.0142, cost=0.261] \n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.67it/s, accuracy=0, cost=0.224]      \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 0.248327, training avg acc 0.005151\n",
      "epoch 3, testing avg loss 0.255450, testing avg acc 0.003196\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.44it/s, accuracy=0.0319, cost=0.253] \n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.65it/s, accuracy=0.0129, cost=0.232] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 0.240196, training avg acc 0.020250\n",
      "epoch 4, testing avg loss 0.260763, testing avg acc 0.007725\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.44it/s, accuracy=0.078, cost=0.238] \n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.61it/s, accuracy=0.0129, cost=0.24]  \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 0.225537, training avg acc 0.067153\n",
      "epoch 5, testing avg loss 0.272367, testing avg acc 0.018334\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.43it/s, accuracy=0.195, cost=0.211] \n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.61it/s, accuracy=0.0452, cost=0.258]\n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 0.203671, training avg acc 0.162199\n",
      "epoch 6, testing avg loss 0.290515, testing avg acc 0.036583\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.43it/s, accuracy=0.365, cost=0.182]\n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.66it/s, accuracy=0.0516, cost=0.282]\n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 0.177396, training avg acc 0.287097\n",
      "epoch 7, testing avg loss 0.317477, testing avg acc 0.072228\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.43it/s, accuracy=0.443, cost=0.148]\n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.65it/s, accuracy=0.103, cost=0.321] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 0.151854, training avg acc 0.402537\n",
      "epoch 8, testing avg loss 0.356769, testing avg acc 0.102667\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.42it/s, accuracy=0.571, cost=0.122]\n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.58it/s, accuracy=0.11, cost=0.361]  \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 0.128955, training avg acc 0.500623\n",
      "epoch 9, testing avg loss 0.398493, testing avg acc 0.111438\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.42it/s, accuracy=0.582, cost=0.102] \n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.65it/s, accuracy=0.135, cost=0.421] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 0.110343, training avg acc 0.574596\n",
      "epoch 10, testing avg loss 0.457165, testing avg acc 0.138099\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.43it/s, accuracy=0.532, cost=0.101] \n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.65it/s, accuracy=0.0839, cost=0.452]\n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 0.094866, training avg acc 0.633989\n",
      "epoch 11, testing avg loss 0.505708, testing avg acc 0.099099\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.43it/s, accuracy=0.645, cost=0.0773]\n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.64it/s, accuracy=0.0839, cost=0.495]\n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 0.083911, training avg acc 0.674366\n",
      "epoch 12, testing avg loss 0.558003, testing avg acc 0.077336\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.43it/s, accuracy=0.798, cost=0.06]  \n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.66it/s, accuracy=0.116, cost=0.541] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 0.072917, training avg acc 0.712523\n",
      "epoch 13, testing avg loss 0.596416, testing avg acc 0.117849\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:49<00:00,  3.42it/s, accuracy=0.794, cost=0.0595]\n",
      "minibatch loop: 100%|██████████| 145/145 [00:17<00:00,  8.49it/s, accuracy=0.161, cost=0.595]\n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 0.065610, training avg acc 0.737632\n",
      "epoch 14, testing avg loss 0.634937, testing avg acc 0.159761\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:56<00:00,  3.27it/s, accuracy=0.599, cost=0.0775]\n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.60it/s, accuracy=0.11, cost=0.584]  \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 0.060682, training avg acc 0.755263\n",
      "epoch 15, testing avg loss 0.646741, testing avg acc 0.103789\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.43it/s, accuracy=0.741, cost=0.0466]\n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.59it/s, accuracy=0.071, cost=0.63]  \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 0.054130, training avg acc 0.777972\n",
      "epoch 16, testing avg loss 0.707160, testing avg acc 0.068564\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:49<00:00,  3.42it/s, accuracy=0.858, cost=0.0818]\n",
      "minibatch loop: 100%|██████████| 145/145 [00:17<00:00,  8.35it/s, accuracy=0.161, cost=0.701]\n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 0.048324, training avg acc 0.796035\n",
      "epoch 17, testing avg loss 0.731096, testing avg acc 0.179190\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.42it/s, accuracy=0.833, cost=0.0343]\n",
      "minibatch loop: 100%|██████████| 145/145 [00:19<00:00,  7.42it/s, accuracy=0.181, cost=0.732]\n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 0.046448, training avg acc 0.802126\n",
      "epoch 18, testing avg loss 0.783001, testing avg acc 0.167646\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:55<00:00,  3.28it/s, accuracy=0.791, cost=0.0392]\n",
      "minibatch loop: 100%|██████████| 145/145 [00:17<00:00,  8.52it/s, accuracy=0.135, cost=0.772] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 0.043719, training avg acc 0.812243\n",
      "epoch 19, testing avg loss 0.852649, testing avg acc 0.110365\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [02:48<00:00,  3.42it/s, accuracy=0.837, cost=0.0352]\n",
      "minibatch loop: 100%|██████████| 145/145 [00:16<00:00,  8.68it/s, accuracy=0.135, cost=0.8]   "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 0.042226, training avg acc 0.816797\n",
      "epoch 20, testing avg loss 0.871126, testing avg acc 0.131413\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x, _ = pad_sentence_batch(train_X[i : index], 0)\n",
    "        batch_y, _ = pad_sentence_batch(train_Y[i : index], 0)\n",
    "        batch_clss, _ = pad_sentence_batch(train_clss[i : index], -1)\n",
    "        batch_clss = np.array(batch_clss)\n",
    "        batch_mask = 1 - (batch_clss == -1)\n",
    "        batch_clss[batch_clss == -1] = 0\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,\n",
    "                model.mask: batch_mask,\n",
    "                model.clss: batch_clss}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x, _ = pad_sentence_batch(test_X[i : index], 0)\n",
    "        batch_y, _ = pad_sentence_batch(test_Y[i : index], 0)\n",
    "        batch_clss, _ = pad_sentence_batch(test_clss[i : index], -1)\n",
    "        batch_clss = np.array(batch_clss)\n",
    "        batch_mask = 1 - (batch_clss == -1)\n",
    "        batch_clss[batch_clss == -1] = 0\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,\n",
    "                model.mask: batch_mask,\n",
    "                model.clss: batch_clss}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import rouge\n",
    "from tensorflow.keras.preprocessing import sequence\n",
    "\n",
    "def calculate_rouges(predicted, batch_y):\n",
    "    non = np.count_nonzero(batch_y, axis = 1)\n",
    "    o = []\n",
    "    for n in non:\n",
    "        o.append([True for _ in range(n)])\n",
    "    b = sequence.pad_sequences(o, dtype = np.bool, padding = 'post', value = False)\n",
    "    batch_y = np.array(batch_y)\n",
    "    rouges = []\n",
    "    for i in range(predicted.shape[0]):\n",
    "        a = batch_y[i][b[i]]\n",
    "        p = predicted[i][b[i]]\n",
    "        rouges.append(rouge.rouge_n([p], [a]))\n",
    "    return np.mean(rouges)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_x, _ = pad_sentence_batch(test_X[: 5], 0)\n",
    "batch_y, _ = pad_sentence_batch(test_Y[: 5], 0)\n",
    "batch_clss, _ = pad_sentence_batch(test_clss[: 5], -1)\n",
    "batch_clss = np.array(batch_clss)\n",
    "batch_y = np.array(batch_y)\n",
    "batch_x = np.array(batch_x)\n",
    "cp_batch_clss = batch_clss.copy()\n",
    "batch_mask = 1 - (batch_clss == -1)\n",
    "batch_clss[batch_clss == -1] = 0\n",
    "\n",
    "feed = {model.X: batch_x,\n",
    "        model.mask: batch_mask,\n",
    "        model.clss: batch_clss}\n",
    "predicted = sess.run(tf.round(tf.sigmoid(model.logits)), feed_dict = feed)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.02314938"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from tensor2tensor.utils import rouge\n",
    "\n",
    "def calculate_rouge(predicted, batch_y, cp_batch_clss, batch_x):\n",
    "    f, y_, predicted_ = [], [], []\n",
    "    for i in range(len(cp_batch_clss)):\n",
    "        f.append(cp_batch_clss[i][cp_batch_clss[i] != -1])\n",
    "        y_.append(batch_y[i][cp_batch_clss[i] != -1])\n",
    "        predicted_.append(predicted[i][cp_batch_clss[i] != -1])\n",
    "    \n",
    "    actual, predict = [], []\n",
    "    for i in range(len(f)):\n",
    "        actual_, predict_ = [], []\n",
    "        for k in range(len(f[i])):\n",
    "            if k == (len(f[i]) - 1):\n",
    "                s = batch_x[i][f[i][k]:]\n",
    "                s = s[s != 0]\n",
    "            else:\n",
    "                s = batch_x[i][f[i][k]: f[i][k + 1]]\n",
    "            s = [w for w in s if w not in [0, 1, 2, 3, 5, 6, 7, 8]]\n",
    "            if y_[i][k]:\n",
    "                actual_.extend(s)\n",
    "            if predicted_[i][k]:\n",
    "                predict_.extend(s)\n",
    "        actual.append(actual_)\n",
    "        predict.append(predict_)\n",
    "    return rouge.rouge_n(predict, actual)\n",
    "\n",
    "calculate_rouge(predicted, batch_y, cp_batch_clss, batch_x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tqdm import tqdm as tqdm_base\n",
    "def tqdm(*args, **kwargs):\n",
    "    if hasattr(tqdm_base, '_instances'):\n",
    "        for instance in list(tqdm_base._instances):\n",
    "            tqdm_base._decr_instances(instance)\n",
    "    return tqdm_base(*args, **kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [03:33<00:00,  2.71it/s, rouge=0.186]\n"
     ]
    }
   ],
   "source": [
    "rouges = []\n",
    "\n",
    "pbar = tqdm(\n",
    "    range(0, len(test_X), 32), desc = 'minibatch loop')\n",
    "for i in pbar:\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x, _ = pad_sentence_batch(test_X[i: index], 0)\n",
    "    batch_y, _ = pad_sentence_batch(test_Y[i: index], 0)\n",
    "    batch_clss, _ = pad_sentence_batch(test_clss[i: index], -1)\n",
    "    batch_clss = np.array(batch_clss)\n",
    "    batch_y = np.array(batch_y)\n",
    "    batch_x = np.array(batch_x)\n",
    "    cp_batch_clss = batch_clss.copy()\n",
    "    batch_mask = 1 - (batch_clss == -1)\n",
    "    batch_clss[batch_clss == -1] = 0\n",
    "\n",
    "    feed = {model.X: batch_x,\n",
    "            model.mask: batch_mask,\n",
    "            model.clss: batch_clss}\n",
    "    predicted = sess.run(tf.round(tf.sigmoid(model.logits)), feed_dict = feed)\n",
    "    rouge_ = calculate_rouge(predicted, batch_y, cp_batch_clss, batch_x)\n",
    "    rouges.append(rouge_)\n",
    "    pbar.set_postfix(rouge = rouge_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.1554709"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.mean(rouges)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
